package com.company.array;

import java.util.*;

/**
 * @author jrue
 * @description https://leetcode-cn.com/problems/intersection-of-two-arrays/
 * 给定两个数组，编写一个函数来计算它们的交集。
 * @date 2019/11/14 11:16
 */
public class Intersection {

    public static void main(String[] args) {
        int[] integers = intersection(new int[]{1, 2, 2, 1}, new int[]{2, 2});
        for (int i = 0; i < integers.length; i++) {
            System.out.println(integers[i]);
        }
    }

    public static int[] intersection(int[] nums1, int[] nums2) {
        int[] tempNum = nums1.length > nums2.length ? nums2 : nums1;
        int[] mapNum = nums1.length > nums2.length ? nums1 : nums2;
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < mapNum.length; i++) {
            map.put(mapNum[i], 1);
        }

        Set<Integer> res = new TreeSet<>();
        for (int i = 0; i < tempNum.length; i++) {
            if (map.get(tempNum[i]) != null) {
                res.add(tempNum[i]);
            }
        }

        Integer[] resInt = new Integer[res.size()];
        Integer[] integers = res.toArray(resInt);
        int[] r = new int[res.size()];
        for (int i = 0; i < integers.length; i++) {
            r[i] = integers[i];
        }
        return r;
    }
}
